#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2021/7/19 14:19
# @Author  : Samge
import pymssql
from itkz.resources.db.base import BaseLogDb


class MsSqlBase(BaseLogDb):

    def __init__(self, host, user, password, database):
        host = self.__tuple_to_str(host)
        user = self.__tuple_to_str(user)
        password = self.__tuple_to_str(password)
        database = self.__tuple_to_str(database)

        self.log_info('{} {} {} {}'.format(host, user, password, database))

        try:
            self.conn = pymssql.connect(host=host, user=user, password=password, database=database)
            self.cursor = self.conn.cursor()
        except Exception as e:
            self.log_error(e)
            pass

    def ExecList(self, sql):
        try:
            cur = self.cursor
            cur.execute(sql)
            columns = [col[0] for col in cur.description]
            return [dict(zip(columns, self.parse_encoding(row))) for row in cur.fetchall()]
        except Exception as e:
            # self.log_error(e)
            return []

    # 添加、更新、删除
    def ExecNonQuery(self, sql):
        try:
            cur = self.cursor
            cur.execute(sql)
            self.conn.commit()
            return True
        except Exception as e:
            self.log_error(e)
            return False

